const db = uniCloud.database();
const dbCmd = db.command;
const enrollmentCollection = db.collection('enrollment');

module.exports = {
  _before: function() {
    // 通用前置处理
  },
  
  /**
   * 获取报名列表
   * @param {Object} params - 查询参数
   * @param {String} params.student_id - 学生ID（可选）
   * @param {String} params.course_id - 课程ID（可选）
   * @param {Number} params.status - 状态（可选）
   * @param {Number} params.page - 页码
   * @param {Number} params.pageSize - 每页数量
   * @returns {Object} 报名列表和总数
   */
  async getEnrollmentList(params = {}) {
    const { student_id, course_id, status, page = 1, pageSize = 10 } = params;
    
    // 构建查询条件
    const query = {};
    if (student_id) query.student_id = student_id;
    if (course_id) query.course_id = course_id;
    if (status !== undefined) query.status = status;
    
    // 查询总数
    const countResult = await enrollmentCollection.where(query).count();
    const total = countResult.total;
    
    // 查询分页数据
    const list = await enrollmentCollection
      .aggregate()
      .match(query)
      .lookup({
        from: 'student',
        localField: 'student_id',
        foreignField: '_id',
        as: 'student'
      })
      .lookup({
        from: 'course',
        localField: 'course_id',
        foreignField: '_id',
        as: 'course'
      })
      .project({
        _id: 1,
        student_id: 1,
        course_id: 1,
        fee: 1,
        discount: 1,
        status: 1,
        enroll_date: 1,
        create_date: 1,
        update_date: 1,
        student: { $arrayElemAt: ['$student', 0] },
        course: { $arrayElemAt: ['$course', 0] }
      })
      .skip((page - 1) * pageSize)
      .limit(pageSize)
      .sort({
        create_date: -1
      })
      .end()
      .then(res => res.data);
    
    return {
      list,
      total,
      page,
      pageSize
    };
  },
  
  /**
   * 获取报名详情
   * @param {String} id - 报名ID
   * @returns {Object} 报名详情
   */
  async getEnrollmentDetail(id) {
    if (!id) throw new Error('报名ID不能为空');
    
    const enrollment = await enrollmentCollection
      .aggregate()
      .match({
        _id: id
      })
      .lookup({
        from: 'student',
        localField: 'student_id',
        foreignField: '_id',
        as: 'student'
      })
      .lookup({
        from: 'course',
        localField: 'course_id',
        foreignField: '_id',
        as: 'course'
      })
      .project({
        _id: 1,
        student_id: 1,
        course_id: 1,
        fee: 1,
        discount: 1,
        status: 1,
        enroll_date: 1,
        create_date: 1,
        update_date: 1,
        student: { $arrayElemAt: ['$student', 0] },
        course: { $arrayElemAt: ['$course', 0] }
      })
      .end()
      .then(res => res.data[0]);
    
    if (!enrollment) throw new Error('报名记录不存在');
    
    return enrollment;
  },
  
  /**
   * 创建报名
   * @param {Object} data - 报名数据
   * @returns {Object} 创建结果
   */
  async createEnrollment(data) {
    // 验证数据
    const { student_id, course_id, fee } = data;
    if (!student_id) throw new Error('学生ID不能为空');
    if (!course_id) throw new Error('课程ID不能为空');
    if (fee === undefined) throw new Error('应缴费金额不能为空');
    
    // 检查学生和课程是否存在
    const student = await db.collection('student').doc(student_id).get().then(res => res.data[0]);
    if (!student) throw new Error('学生不存在');
    
    const course = await db.collection('course').doc(course_id).get().then(res => res.data[0]);
    if (!course) throw new Error('课程不存在');
    
    // 检查学生和课程状态
    if (student.status !== 1) throw new Error('学生状态不是在读状态，无法报名');
    if (course.status !== 1) throw new Error('课程未激活，无法报名');
    
    // 检查是否已报名
    const existingEnrollment = await enrollmentCollection
      .where({
        student_id,
        course_id,
        status: 1
      })
      .count();
    
    if (existingEnrollment.total > 0) {
      throw new Error('该学生已报名此课程');
    }
    
    // 创建报名记录
    const result = await enrollmentCollection.add({
      ...data,
      discount: data.discount || 0,
      status: 1,
      enroll_date: data.enroll_date || new Date(),
      create_date: new Date(),
      update_date: new Date()
    });
    
    return {
      id: result.id,
      success: true
    };
  },
  
  /**
   * 更新报名
   * @param {String} id - 报名ID
   * @param {Object} data - 更新数据
   * @returns {Object} 更新结果
   */
  async updateEnrollment(id, data) {
    if (!id) throw new Error('报名ID不能为空');
    
    // 检查报名记录是否存在
    const enrollment = await enrollmentCollection.doc(id).get().then(res => res.data[0]);
    if (!enrollment) throw new Error('报名记录不存在');
    
    // 更新报名记录
    await enrollmentCollection.doc(id).update({
      ...data,
      update_date: new Date()
    });
    
    return {
      id,
      success: true
    };
  },
  
  /**
   * 取消报名
   * @param {String} id - 报名ID
   * @returns {Object} 取消结果
   */
  async cancelEnrollment(id) {
    if (!id) throw new Error('报名ID不能为空');
    
    // 检查报名记录是否存在
    const enrollment = await enrollmentCollection.doc(id).get().then(res => res.data[0]);
    if (!enrollment) throw new Error('报名记录不存在');
    
    // 检查是否有缴费记录
    const paymentCount = await db.collection('payment')
      .where({
        enrollment_id: id,
        status: dbCmd.neq(0)
      })
      .count();
    
    if (paymentCount.total > 0) {
      throw new Error('该报名记录已有缴费记录，无法直接取消，请先处理相关缴费');
    }
    
    // 取消报名
    await enrollmentCollection.doc(id).update({
      status: 0,
      update_date: new Date()
    });
    
    return {
      id,
      success: true
    };
  },
  
  /**
   * 获取学生已报名的课程
   * @param {String} student_id - 学生ID
   * @returns {Array} 已报名课程列表
   */
  async getStudentEnrollments(student_id) {
    if (!student_id) throw new Error('学生ID不能为空');
    
    return await enrollmentCollection
      .aggregate()
      .match({
        student_id,
        status: 1
      })
      .lookup({
        from: 'course',
        localField: 'course_id',
        foreignField: '_id',
        as: 'course'
      })
      .project({
        _id: 1,
        student_id: 1,
        course_id: 1,
        fee: 1,
        discount: 1,
        status: 1,
        enroll_date: 1,
        course: { $arrayElemAt: ['$course', 0] }
      })
      .end()
      .then(res => res.data);
  },
  
  /**
   * 获取课程已报名的学生
   * @param {String} course_id - 课程ID
   * @returns {Array} 已报名学生列表
   */
  async getCourseEnrollments(course_id) {
    if (!course_id) throw new Error('课程ID不能为空');
    
    return await enrollmentCollection
      .aggregate()
      .match({
        course_id,
        status: 1
      })
      .lookup({
        from: 'student',
        localField: 'student_id',
        foreignField: '_id',
        as: 'student'
      })
      .project({
        _id: 1,
        student_id: 1,
        course_id: 1,
        fee: 1,
        discount: 1,
        status: 1,
        enroll_date: 1,
        student: { $arrayElemAt: ['$student', 0] }
      })
      .end()
      .then(res => res.data);
  }
}; 